package com.fate.framework.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;

/** http工具类 */
@Slf4j
public class HttpUtil {
  /**
   * 发起一个GET请求
   *
   * @param urlString 地址
   * @return 结果
   */
  public static String sendGet(String urlString) throws Exception {
    return sendRequest(urlString, "GET", null, null);
  }

  /**
   * 发起一个POST请求
   *
   * @param urlString 地址
   * @param params 参数传递map
   * @param headers 头部传递map
   * @return 结果
   */
  public static String sendPost(
      String urlString, Map<String, Object> params, Map<String, String> headers) throws Exception {
    // Convert the parameters map to a URL-encoded string
    StringJoiner sj = new StringJoiner("&");
    for (Map.Entry<String, Object> entry : params.entrySet()) {
      sj.add(entry.getKey() + "=" + entry.getValue());
    }
    String payload = sj.toString();

    return sendRequest(urlString, "POST", payload, headers);
  }

  /**
   * 发起一个POST请求
   *
   * @param urlString 地址
   * @param params 参数传递map
   * @return 结果
   */
  public static String sendPost(String urlString, Map<String, Object> params) throws Exception {
    // Convert the parameters map to a URL-encoded string
    StringJoiner sj = new StringJoiner("&");
    for (Map.Entry<String, Object> entry : params.entrySet()) {
      sj.add(entry.getKey() + "=" + entry.getValue());
    }
    String payload = sj.toString();
    Map<String, String> headerMap = new HashMap<>();
    headerMap.put("Content-Type", "application/json;charset=UTF-8");
    return sendRequest(urlString, "POST", payload, headerMap);
  }

  public static String sendPostJson(String urlString, Map<String, Object> params) throws Exception {
    // Map转json
    String payload = JSON.toJSONString(params);

    Map<String, String> headerMap = new HashMap<>();
    headerMap.put("Content-Type", "application/json;charset=UTF-8");
    return sendRequest(urlString, "POST", payload, headerMap);
  }

  // Private method to handle HTTP requests
  private static String sendRequest(
      String urlString, String method, String payload, Map<String, String> headers)
      throws Exception {
    URL url = new URL(urlString);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(method);

    // Add headers if provided
    if (headers != null) {
      for (Map.Entry<String, String> entry : headers.entrySet()) {
        conn.setRequestProperty(entry.getKey(), entry.getValue());
      }
    }

    // Write payload for POST request
    if ("POST".equals(method)) {
      conn.setDoOutput(true);
      if (payload != null) {
        try (OutputStream os = conn.getOutputStream()) {
          os.write(payload.getBytes());
          os.flush();
        }
      }
    }

    int responseCode = conn.getResponseCode();
    if (responseCode == HttpURLConnection.HTTP_OK) {
      try (InputStream in = conn.getInputStream();
          ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
        byte[] buffer = new byte[1024];
        while (in.read(buffer) != -1) {
          byteArrayOutputStream.write(buffer);
        }

        // 尝试将字节数组转换为字符串
        String responseString = byteArrayOutputStream.toString(StandardCharsets.UTF_8);
        log.info("Response: {}", responseString);

        return responseString;
      } catch (Exception e) {
        log.error("Error reading response", e);
        throw e;
      }
    } else {
      throw new Exception(method + " request failed: " + responseCode);
    }
  }

  public static String sendPost01(String urlString, Map<String, Object> params) throws Exception {
    // 将参数转换为 JSON 格式字符串
    JSONObject jsonParams = new JSONObject(params);
    String payload = jsonParams.toString();
    // 创建连接
    URL url = new URL(urlString);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    // 设置请求头
    connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
    connection.setDoOutput(true);
    // 写入请求体
    try (OutputStream os = connection.getOutputStream()) {
      byte[] input = payload.getBytes(StandardCharsets.UTF_8);
      os.write(input, 0, input.length);
    }
    // 读取响应
    try (java.io.InputStream in = connection.getInputStream()) {
      java.util.Scanner scanner = new java.util.Scanner(in).useDelimiter("\\A");
      return scanner.hasNext() ? scanner.next() : "";
    }
  }
}
